package com.project.easy.common.util.util;

import com.project.easy.common.util.exception.sys.SysInitException;
import com.project.easy.common.util.string.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @ClassName IPUtil
 * @Description
 * @Author GreatorMan.cool
 * @Date 2021/3/25 16:28
 * @Version 1.0
 **/
public class IPUtil {

	private static final String UNKNOWN = "unknown";

	protected IPUtil() {
	}

	/**
	 * @param ip ip IP
	 * @return 返回IP转换为整数
	 * @throws SysInitException  返回系统初始化失败异常
	 */
	public  static  Integer convertToInt(String ip) throws  SysInitException {
		if (StringUtil.isBlank(ip)) {
			return 0;
		}
		return Long.valueOf(Long.valueOf(ip.replace(".", "")) % Integer.MAX_VALUE).intValue();
	}

	/**
	 * @return 返回IP
	 * @throws SysInitException 系统初始化异常，本类型异常会导致系统初始化失败
	 */
	public  static  String getLocalIp() throws  SysInitException {
		try {
			InetAddress address = InetAddress.getLocalHost();
			String hostAddress = address.getHostAddress();
			return hostAddress;
		} catch (Exception e) {
			throw new SysInitException("获取IP失败");
		}
	}

	/**
	 * 获取IP地址
	 * 使用 Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非 unknown的有效IP字符串，则为真实IP地址
	 * @return String
	 * @param request  请求参数
	 */
	public static String getIpAddr(final HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}

}
